package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.UserRequest;
import com.jdone.compus.service.WxTokenService;
import com.jdone.compus.utils.SignatureUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/compus")
@Api(value = "校园系统接口", tags = "校园系统接口")
public class ApiProxyController {

    @Autowired
    private  WxTokenService wxTokenService;

    @Value("${compus.url}")
    private String url;

    @Value("${compus.appSecret}")
    private String appSecret;

    @Value("${compus.appKey}")
    private String appKey;

    @ApiOperation(value = "校园用户注册查询")
    @PostMapping("/user-info")
    public ResponseEntity<String> proxyUserInfoRequest(@RequestBody UserRequest userRequest) throws Exception {
       // System.out.println("请求进来");

        // Generate timestamp and randStr
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String randStr = generateRandomString(16);

        String encryptionType = userRequest.getEncryptionType() != null ? userRequest.getEncryptionType() : "sha1";
        String signature = SignatureUtil.generateSignature(appSecret, timestamp, randStr, encryptionType);

        // Prepare headers and form-data
        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", appKey);
        headers.put("timestamp", timestamp);
        headers.put("randStr", randStr);
        headers.put("sign", signature);
        headers.put("encryptionType", encryptionType);

        Map<String, String> formData = new HashMap<>();
        formData.put("tenantCode", userRequest.getTenantCode());
        formData.put("userCode", userRequest.getUserCode());
        formData.put("userType", userRequest.getUserType());

        // Send POST request
        String response = sendPostRequest(url, headers, formData);
        return ResponseEntity.ok(response);
    }

    private String sendPostRequest(String urlString, Map<String, String> headers, Map<String, String> formData) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        // Set headers
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }

        // Prepare form data
        String formDataString = formData.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));

        // Send form data
        try (OutputStream os = connection.getOutputStream()) {
            os.write(formDataString.getBytes(StandardCharsets.UTF_8));
        }

        // Get response
        try (InputStream is = connection.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        }
    }

    private String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randStr = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            randStr.append(chars.charAt(index));
        }
        return randStr.toString();
    }



    @ApiOperation(value = "获取微信 token")
    @GetMapping("/wx-token")
    public ApiResponse getWxToken() {
        try {
            String token = wxTokenService.fetchWxToken();
            if (token == null) {
                return new ApiResponse(500, false, "无法从外部服务获取 token，返回为空", null);
            }
            return new ApiResponse(200, true, "获取成功", token);
        } catch (Exception e) {
            return new ApiResponse(500, false, "调用外部服务异常: " + e.getMessage(), null);
        }
    }



    @ApiOperation("代理获取微信 ticket（GET） — 参数：access_token, type（可选）")
    @GetMapping("/getTicket")
    public ApiResponse getTicketGet(@RequestParam("access_token") String accessToken) {
        try {
            Map<String, Object> data = wxTokenService.getTicket(accessToken, "jsapi");
            return ApiResponse.success(data);
        } catch (IllegalArgumentException iae) {
            return ApiResponse.error(iae.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("调用微信失败: " + e.getMessage());
        }
    }

    @ApiOperation("代理获取微信 ticket（POST JSON） — body: {\"access_token\":\"xxx\",\"type\":\"jsapi\"}")
    @PostMapping("/getTicket")
    public ApiResponse getTicketPost(@RequestBody Map<String, String> body) {
        try {
            if (body == null || !body.containsKey("access_token")) {
                return ApiResponse.error("access_token 不能为空");
            }
            String accessToken = body.get("access_token");
            String type = body.getOrDefault("type", "jsapi");
            Map<String, Object> data = wxTokenService.getTicket(accessToken, type);
            return ApiResponse.success(data);
        } catch (IllegalArgumentException iae) {
            return ApiResponse.error(iae.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("调用微信失败: " + e.getMessage());
        }
    }

}
